package
{
	import com.json.JSON;
	
	import mx.collections.ArrayCollection;
	import mx.containers.ViewStack;
	import mx.rpc.events.ResultEvent;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import services.mainservice.MainService;
	import services.userservice.UserService;
	
	public class EasyMediator extends Mediator implements IMediator
	{
		public static const EASY_MEDIATOR:String = "EASY_MEDIATOR";
		public static const CHANGE_VIEW:String = "CHANGE_VIEW";
		
		public function EasyMediator(viewComponent:Object)
		{
			super(EASY_MEDIATOR, viewComponent);
		}
		
		override public function listNotificationInterests():Array {
			return [
				CHANGE_VIEW
			];
		}
		
		override public function handleNotification(notification:INotification):void {
			switch(notification.getName()) {
				case CHANGE_VIEW:
					switch(GlobalObject.currentOperater) {
						case OperateEnum.USER:
							var userService:UserService = new UserService();
							this.views.selectedIndex = 0;
							userService.addEventListener(ResultEvent.RESULT,userFunction);
							userService.getUsers();
							break;
						case OperateEnum.COMPANY:
							this.views.selectedIndex = 1;
							break;
						case OperateEnum.NEWS:
							this.views.selectedIndex = 2;
							break;
						case OperateEnum.CONTACT:
							this.views.selectedIndex = 3;
							var service:MainService = new MainService();
							service.addEventListener(ResultEvent.RESULT,contactFunction);
							service.getContacts();
							break;
					}
					break;
			}
		}
		
		private function contactFunction(evt:ResultEvent):void {
			var contacts:Array = com.json.JSON.decode(evt.result as String);
			var arr:ArrayCollection = new ArrayCollection();
			
			for each(var contact:Object in contacts) {
				arr.addItem({id:contact.id,label:contact.name,phone:contact.phone,mail:contact.mail});
			}
			this.easyClient.contacts.dataProvider = arr;
		}
		
		private function userFunction(evt:ResultEvent):void {
			var users:Array = com.json.JSON.decode(evt.result as String);
			var arr:ArrayCollection = new ArrayCollection();
			
			for each(var user:Object in users) {
				arr.addItem({id:user.id,label:user.username,password:user.password});
			}
			this.easyClient.users.dataProvider = arr;
		}
		
		public function get easyClient():EasyClient {
			return this.viewComponent as EasyClient;
		}
		
		public function get views():ViewStack {
			return this.easyClient.views;
		}
		
	}
}